package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.shopping.AddressForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.OrderDetailRequest;
import com.mall.order.dto.OrderDetailResponse;
import com.mall.shopping.IProductCateService;
import com.mall.shopping.IProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.IAddressService;
import com.mall.user.annotation.Anonymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * create by ciggar on 2020/03/05
 */
@Slf4j
@RestController
@RequestMapping("/shopping")
@Api(tags = "AddressController", description = "地址控制层")
public class AddressController {

    @Reference(timeout = 3000, check = false)
    IAddressService addressService;

    @Reference(timeout = 3000, check = false)
    IProductService iProductService;

    @Reference(timeout = 3000, check = false)
    IProductCateService iProductCateService;

    @Reference(timeout = 3000, check = false)
    OrderQueryService orderQueryService;

    /**
     * 获取当前用户的地址列表
     *
     * @return
     */
    @GetMapping("/addresses")
    @ApiOperation("获取当前用户的地址列表")
    public ResponseData addressList(HttpServletRequest request) {
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        AddressListRequest addressListRequest = new AddressListRequest();

        addressListRequest.setUserId(uid);
        AddressListResponse response = addressService.addressList(addressListRequest);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getAddressDtos());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @ApiOperation("添加地址")
    @PostMapping("/addresses")
    @ApiImplicitParam(name = "form", value = "地址信息", dataType = "AddressForm", required = true)
    public ResponseData addressAdd(@RequestBody AddressForm form, HttpServletRequest servletRequest) {
        log.debug(form.is_Default() + "");
        log.debug(form.toString());

        AddAddressRequest request = new AddAddressRequest();
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        request.setUserId(uid);
        request.setUserName(form.getUserName());
        request.setStreetName(form.getStreetName());
        request.setTel(form.getTel());
        request.setIsDefault(form.is_Default() ? 1 : null);
        AddAddressResponse response = addressService.createAddress(request);

        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @ApiOperation("删除地址")
    @DeleteMapping("/addresses/{addressid}")
    @ApiImplicitParam(name = "addressid", value = "地址ID", paramType = "path", required = true)
    public ResponseData addressDel(@PathVariable("addressid") Long addressid) {
        DeleteAddressRequest request = new DeleteAddressRequest();
        request.setAddressId(addressid);
        DeleteAddressResponse response = addressService.deleteAddress(request);

        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());

    }

    @ApiOperation("更新地址")
    @PutMapping("/addresses")
    @ApiImplicitParam(name = "form", value = "地址信息", dataType = "AddressForm", required = true)
    public ResponseData addressUpdate(@RequestBody AddressForm form, HttpServletRequest servletRequest) {
        UpdateAddressRequest request = new UpdateAddressRequest();
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        request.setAddressId(form.getAddressId());
        request.setIsDefault(form.is_Default() ? 1 : null);
        request.setStreetName(form.getStreetName());
        request.setTel(form.getTel());
        request.setUserId(uid);
        request.setUserName(form.getUserName());

        UpdateAddressResponse response = addressService.updateAddress(request);

        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @ApiOperation("分页查询商品")
    @GetMapping("goods")
    @Anonymous //匿名请求
    public ResponseData goods(Integer page, Integer size, Long cid, String sort, Integer priceGt, Integer priceLte) {

        AllProductRequest request = new AllProductRequest();
        request.setCid(cid);
        request.setPage(page);
        request.setSize(size);
        request.setSort(sort);
        request.setPriceGt(priceGt);
        request.setPriceLte(priceLte);

        AllProductResponse allProductByPage = iProductService.getAllProductByPage(request);

        //TODO 校验
        ResponseUtil responseUtil = new ResponseUtil();

        HashMap<String, Object> map = new HashMap<>();
        map.put("data", allProductByPage.getProductDtoList());
        map.put("total", allProductByPage.getTotal());

        return responseUtil.setData(map);
    }

    @ApiOperation("查询推荐商品")
    @GetMapping("recommend")
    @Anonymous
    public ResponseData getRecommendGoods() {
        RecommendResponse recommendGoods = iProductService.getRecommendGoods();

        ResponseUtil responseUtil = new ResponseUtil();
        return responseUtil.setData(recommendGoods.getPanelContentItemDtos());
    }

    @ApiOperation("查询商品所有分类信息")
    @Anonymous //匿名请求
    @GetMapping("categories")
    public ResponseData getCategories() {
        AllProductCateResponse allProductCate = iProductCateService.getAllProductCate(new AllProductCateRequest());
        return new ResponseUtil().setData(allProductCate.getProductCateDtoList());
    }

    @ApiOperation("根据Id查看订单状态")
    @GetMapping("order/{orderId}")
    public ResponseData queryOrdersDetailsById(@PathVariable("orderId") String orderId) {

        OrderDetailRequest request = new OrderDetailRequest();
        request.setOrderId(orderId);
        OrderDetailResponse response = orderQueryService.queryOrdersById(request);

        // 做判断
        String code = response.getCode();

        if (OrderRetCode.SUCCESS.getCode().equals(code)) {
            return new ResponseUtil().setData(response);
        }
        return new ResponseUtil().setErrorMsg(Integer.valueOf(response.getCode()), response.getMsg());
    }

    @ApiOperation("根据关键词查询商品")
    @PostMapping("search")
    public String searchByKeyword(@RequestBody Map<String, Object> map) {
        return "功能尚在开发";
    }
}